import pygame
import cv2
import os
import pandas as pd
from settings import Settings
from button import Button
import textboard
import procedure_functions as pf
import face



def run_procedure():
    cdir = os.getcwd()
    path = cdir + '/file/'
    if not os.path.exists(path + '停车场车辆表' + '.xlsx'):
        # 车牌号 进入时间 离开时间 价格 是否业主
        carnfile = pd.DataFrame(columns=['carnumber', 'inDate', 'outData', 'price', 'isOwner', 'validityDate'])
        # 生成xlsx文件
        carnfile.to_excel(path + '停车场车辆表' + '.xlsx', sheet_name='data')
        carnfile.to_excel(path + '停车场历史表' + '.xlsx', sheet_name='data')

    settings = Settings()
    # 初始化并创建一个屏幕对象
    pygame.init()
    pygame.display.set_caption('智能小区车牌识别系统')
    ic_launcher = pygame.image.load("./images/icon_launcher.png")
    # pygame.display.set_icon(ic_launcher)
    screen = pygame.display.set_mode((settings.screen_width, settings.screen_height))

    try:
        # cam = cv2.VideoCapture(0) # 开启摄像头
        cam = cv2.VideoCapture('file/test.mp4')
    except:
        print('请连接摄像头')
    # 循环帧率设置
    clock = pygame.time.Clock()
    running = True

    img = "images/car2.jpg"
    # 开始主循环
    while running:
        screen.fill(settings.bg_color)

        # # 从摄像头读取图片
        # sucess, img = cam.read()
        # # 保存图片，并退出。
        # if sucess:
        #     cv2.imwrite('images/car1.jpg', img)
        # else:
        #     # 识别不到图片或者设备停止，则退出系统
        #     running = False
        # 加载图像

        image = pygame.image.load(img)
        # 设置图片大小
        image = pygame.transform.scale(image, (640, 480))
        # 绘制视频画面
        screen.blit(image, (2, 2))

        # 创建识别按钮
        recognition_button = Button(screen, '识别', 640, 480)
        recognition_button.draw_button()
        select_button = Button(screen, '选择', 100, 480)
        select_button.draw_button()
        # 读取文件内容
        ownerInfo_table = pd.read_excel(path + '住户车辆表.xlsx', sheet_name='data')
        carInfo_table = pd.read_excel(path + '停车场车辆表.xlsx', sheet_name='data')
        history_table = pd.read_excel(path + '停车场历史表.xlsx', sheet_name='data')
        inNumber = len(carInfo_table['carnumber'].values)
        # 绘制背景
        textboard.draw_bg(screen)
        # 绘制信息标题
        textboard.draw_text(screen, '共有车位：' + str(settings.total) + '  剩余车位：' + str(settings.total - inNumber), 680, 0, 20)
        # 绘制信息表头
        textboard.draw_text(screen, ' 车牌号          进入时间', 700, 40, 15)
        # 绘制停车场车辆前十条信息
        carInfos = carInfo_table.sort_values(by='inDate', ascending=False)
        i = 0
        for carInfo in carInfos.values:
            if i >= 10:
                break
            i += 1
            textboard.draw_text(screen, str(carInfo[1]) + '     ' + str(carInfo[2]), 700, 40 + i * 30, 15)
        # 绘制识别信息
        textboard.draw_text(screen, settings.carnumber, 660, 400, 15, settings.ocr_color)
        textboard.draw_text(screen, settings.comeInTime, 660, 422, 15, settings.ocr_color)
        textboard.draw_text(screen, settings.message, 660, 442, 15, settings.ocr_color)

        """ 响应鼠标事件 """
        img = pf.check_events(settings, recognition_button, ownerInfo_table, carInfo_table, history_table, path, img, select_button)
        pygame.display.flip()
        # 控制游戏最大帧率为 60
        clock.tick(60)

    # 关闭摄像头
    # cam.release()

def face_check():
    cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # 开启摄像头
    sucess, img = cam.read()
    if sucess:
        cv2.imwrite('face/try.jpg', img)
    cam.release()
    score = face.analyse_img("face/try.jpg","face/myphoto.jpg")
    print(score)
    if score > 80:
        print('身份对比成功')
        run_procedure()
    else:
        print('身份对比失败')

# run_procedure()
face_check()